package com.zhidisoft.admin.aspect;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zhidisoft.admin.aonn.ServiceLogAnno;
import com.zhidisoft.admin.entity.ServiceLog;
import com.zhidisoft.admin.mapper.IServiceLogMapper;

/**
 * 记录日志 jdk的动态代理不支持类注入，只支持接口方式注入
 * http://www.cnblogs.com/luffyu/p/6425694.html?utm_source=itdadao&utm_medium=referral
 * 
 * @author admin
 *
 */
@Component
@Aspect
public class LogAspect {

	@Autowired
	IServiceLogMapper mapper;

	@Pointcut("execution(* com.zhidisoft.admin.service..*.*(..))")
	private void serviceAspect() {

	}

	@Around("serviceAspect()")
	public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		// System.out.println("方法被调用");
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		//System.out.println(request.getSession().getAttribute("userId"));
		// 拦截的实体类，就是当前正在执行的controller
		Object target = pjp.getTarget();
		// 拦截的方法名称。当前正在执行的方法
		String methodName = pjp.getSignature().getName();

		// 获取方法对象
		MethodSignature msig = (MethodSignature) pjp.getSignature();
		Class<?>[] parameterTypes = msig.getMethod().getParameterTypes();
		Method method = target.getClass().getMethod(methodName, parameterTypes);

		// 获取方法上面的注解
		if (method.isAnnotationPresent(ServiceLogAnno.class)) {
			ServiceLogAnno systemlog = method.getAnnotation(ServiceLogAnno.class);
			// System.out.println(systemlog.value());
			// System.out.println(methodName);
			// System.out.println(">>>>>>>>>");
			ServiceLog log = new ServiceLog();
			log.setId(UUID.randomUUID().toString().replace("-", ""));
			log.setMethod_name(methodName);
			log.setMethod_info(systemlog.value());
			log.setUser_id(request.getSession().getAttribute("userId").toString());
			mapper.save(log);
		} else {// 没有包含注解
			// log.setDescription("此操作不包含注解");
			// log.setState((short) 0);
		}
		return pjp.proceed();
	}

	@Before("execution(* com.zhidisoft.admin.service..*.*(..))")
	public void BlogBefore() {
		// System.out.println("方法执行前记录日志");
	}
}
